package com.fanghuaiming.test.netty.c5.eventloop;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.nio.charset.StandardCharsets;
import lombok.extern.slf4j.Slf4j;

/****
 * @description:
 * @version:1.0.0
 * @author fanghuaiming
 * @data Created in 2021/9/26 下午10:30
 *
 */
@Slf4j
public class EventLoopServer {

  public static void main(String[] args) {
      //细分:创建一个新的EventLoopGroup去执行耗时的操作,而不是让Nio的EventLoopGroup去执行(一个EventLoopGroup可能管理多个channel),以免阻塞其他channel
      DefaultEventLoopGroup group = new DefaultEventLoopGroup();
      new ServerBootstrap()
              //boss worker
              //boss 只负责accept事件 worker只负责 SocketChannel上的读写
              // NioEventLoopGroup的worker只创建了2个线程,如果客户端有3个连接那就会进行多路复用,可能1个线程管理了2个channel
              .group(new NioEventLoopGroup(),new NioEventLoopGroup(2))
              .channel(NioServerSocketChannel.class)
              .childHandler(new ChannelInitializer<NioSocketChannel>() {
                  @Override
                  protected void initChannel(NioSocketChannel ch) throws Exception {
                      //第一个参数代表以后使用的就不是Nio上的NioEventLoopGroup,而是我们后来创建的NioEventLoopGroup
                      ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                          @Override
                          public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                              ByteBuf buf = (ByteBuf) msg;
                              log.info(buf.toString(StandardCharsets.UTF_8));
                              //将消息从当前传递到下一个handler
                              ctx.fireChannelRead(msg);
                          }
                      }).addLast(group,"handler1",new ChannelInboundHandlerAdapter(){
                                  @Override
                                  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                      ByteBuf buf = (ByteBuf) msg;
                                      log.info(buf.toString(StandardCharsets.UTF_8));
                                  }
                              });
                  }
              })
              .bind(8080);
  }
}
